<template>
  <div>
    <n-card class="wrap">
      <div class="wrap-title">个人中心</div>
      <div class="user-detail">
        <n-form
          class="user-detail-form"
          label-placement="left"
          label-width="100px"
          ref="formRef"
          :model="form"
          :rules="rules"
        >
          <n-form-item path="userName" label="用户名:">
            <n-input v-model:value="form.userName" disabled />
          </n-form-item>
          <n-form-item path="realName" label="真实姓名:">
            <n-input v-model:value="form.realName" />
          </n-form-item>
          <n-form-item path="sex" label="性别:">
            <n-select
              v-model:value="form.sex"
              :options="[
                {
                  label: '男',
                  value: 1
                },
                {
                  label: '女',
                  value: 2
                }
              ]"
            />
          </n-form-item>
          <n-form-item
            path="mobile"
            label="手机号:"
            :rule="{
              required: true,
              trigger: 'blur',
              validator: telValidatorFactory(true)
            }"
          >
            <n-input v-model:value="form.mobile" />
          </n-form-item>
          <n-form-item
            path="idCard"
            label="身份证号:"
            :rule="{
              trigger: 'blur',
              validator: IDValidator
            }"
          >
            <n-input-group>
              <n-input
                v-model:value="form.idCard"
                :type="isIDPassword ? 'password' : 'text'"
                :disabled="isIDPassword"
              />
              <n-button style="margin-left: 10px" @click="handleIDedit">
                修改
              </n-button>
            </n-input-group>
          </n-form-item>
          <n-form-item path="orgId" label="所属使馆:">
            <n-select
              v-model:value="form.orgId"
              :options="orgOptions"
              labelField="orgName"
              valueField="orgId"
              disabled
            />
          </n-form-item>
          <n-form-item path="address" label="地址:">
            <n-input v-model:value="form.address" />
          </n-form-item>
          <n-form-item path="postCode" label="邮政编码:">
            <n-input v-model:value="form.postCode" />
          </n-form-item>
          <n-form-item path="phone" label="电话:">
            <n-input v-model:value="form.phone" />
          </n-form-item>
          <n-form-item path="email" label="邮箱:">
            <n-input v-model:value="form.email" />
          </n-form-item>
          <div class="form-btn">
            <pro-return-button
              style="margin-right: 40px"
              @click="backHandle"
            ></pro-return-button>
            <n-button :loading="loading" type="primary" @click="saveHandle">
              <template #icon>
                <icons name="i-save-one" fill="#fff"></icons>
              </template>
              保存
            </n-button>
          </div>
        </n-form>
      </div>
    </n-card>
  </div>
</template>

<script lang="ts" setup name="userDetails">
  import { FormInst, FormRules } from 'naive-ui'
  import { useUser } from '@/store/modules/user'
  import { orgAllByOrgTypeApi, getUserInfoApi } from '@/api/system/user'
  import config from '@/config'
  import { editLoginUserSelfApi } from '@/api/system/user'
  import { IDValidatorFactory, telValidatorFactory } from '@/utils/validator'

  const formRef = ref<FormInst | null>(null)
  const loading = ref(false)
  const user = useUser()
  const { userInfo } = toRefs(user)
  const form = ref({})
  const orgOptions = ref([])
  const fetchOrgAllByOrgTypeApi = async () => {
    const res = await orgAllByOrgTypeApi()
    if (res.code === '0000') {
      orgOptions.value = res.data
    }
  }
  const rules: FormRules = {
    userName: {
      required: true,
      message: '用户名必填！'
    },
    realName: {
      required: true,
      message: '真实姓名必填！'
    }
  }

  // 身份证是否是修改状态（是否点击了右侧的修改按钮）
  const IDedited = ref(false)
  const handleIDedit = () => {
    IDedited.value = true
    form.value.idCard = ''
  }
  // 身份证是否是密文状态
  const isIDPassword = computed(
    () => !!userInfo.value.idCard && !IDedited.value
  )
  // 身份证验证规则，在isIDPassword=true时不进行验证
  const IDValidator = computed(() => {
    return isIDPassword.value ? () => true : IDValidatorFactory(false)
  })

  // 获取用户详情
  const fetchUserInfo = async () => {
    try {
      const res = await getUserInfoApi()
      if (res.code === '0000') {
        form.value = res.data
      }
    } catch (e) {
      console.log(e)
    }
  }

  const backHandle = () => {
    useTabBack()
  }
  const saveHandle = async () => {
    formRef.value?.validate(async (errors) => {
      if (!errors) {
        const res = await editLoginUserSelfApi(form.value)
        loading.value = false
        if (res.code === '0000') {
          window['$message'].success('保存成功！')
          await fetchUserInfo()
          IDedited.value = false
          user.setUserInfo(form.value)
        }
      } else {
        console.log(errors)
      }
    })
  }

  fetchOrgAllByOrgTypeApi()
  fetchUserInfo()
</script>

<style lang="less" scoped>
  .wrap {
    font-size: 14px;
    line-height: 1.6;
    display: flex;
    flex-direction: column;
    width: 100%;
    box-sizing: border-box;
    position: relative;
    border-radius: 6px;
    //background-color: #fff;
    color: #333639;
    padding: 15px 20px;
    word-break: break-word;
    border: 1px solid #efeff5;
    transition: color 0.3s cubic-bezier(0.4, 0, 0.2, 1),
      background-color 0.3s cubic-bezier(0.4, 0, 0.2, 1),
      box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1),
      border-color 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    &:hover {
      box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.08),
        0 3px 6px 0 rgba(0, 0, 0, 0.06), 0 5px 12px 4px rgba(0, 0, 0, 0.04);
    }
    .wrap-title {
      padding-left: 10px;
      font-size: 14px;
      font-weight: 600;
      &::before {
        content: '';
        position: absolute;
        width: 6px;
        height: 20px;
        left: 15px;
        top: 15px;
        background-color: var(--primary-color);
      }
    }
  }
  .user-detail {
    .user-detail-form {
      margin: 20px auto;
      width: 800px;
      display: flex;
      flex-wrap: wrap;
      :deep(.n-form-item) {
        width: 50%;
        box-sizing: border-box;
        padding: 0 10px;
        .n-form-item-label__text {
          font-weight: 600;
        }
      }
      .form-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        margin-top: 10px;
      }
    }
  }
  :deep(.n-card__content) {
    padding: 0 !important;
  }
</style>
